package mongodb

import (
	"beergo/lib/tool"
	"fmt"
	"io/ioutil"
	"strings"
)

func CreateVueAdminFile(creator *Creator) {
	path := root + "/plugins/maker/template/vue/admin"
	target := root + "/var/output/"
	files, err := ioutil.ReadDir(path)
	if err != nil {
		tool.JsonLog(err)
	}
	for _, file := range files {
		content, _ := ioutil.ReadFile(path + "/" + file.Name())
		tpl := string(content)
		tpl = strings.ReplaceAll(tpl, "__DIR__", creator.Table.Path)
		tpl = strings.ReplaceAll(tpl, "__EN_NAME__", creator.Table.Name)
		//默认配置信息输入
		//--form
		if file.Name() == "edit.js" {
			tpl = strings.ReplaceAll(tpl, "__FORM_ITEMS__", makeFormItem(creator))
		}
		//--list
		if file.Name() == "list.js" {
			tpl = strings.ReplaceAll(tpl, "__LIST_ITEMS__", makeListItem(creator))
		}
		tool.CreateDirForPath(target + creator.Table.Path + "/" + creator.Table.Name + "/" + file.Name())
		err := ioutil.WriteFile(target+creator.Table.Path+"/"+creator.Table.Name+"/"+file.Name(), []byte(tpl), 0777)
		if err != nil {
			tool.JsonLog(err)
		}
	}

	content, _ := ioutil.ReadFile(root + "/plugins/maker/template/vue/layout.vue")
	tpl := string(content)
	tpl = strings.ReplaceAll(tpl, "__DIR__", creator.Table.Path)
	tool.CreateDirForPath(target + creator.Table.Path + "/layout.vue")
	err = ioutil.WriteFile(target+creator.Table.Path+"/layout.vue", []byte(tpl), 0777)
	if err != nil {
		tool.JsonLog(err)
	}

	tool.JsonLog(files)
}

func makeFormItem(creator *Creator) string {
	configStr := ""
	for _, field := range creator.Fields {
		var tpl string
		switch field.GetType() {
		case "M2O":
			tpl = `{
        "label": "%s",
        "key": "%s",
        "type": "EzSelectApi",
        "span": 24,
        "placeholder": "请输入",
        "sn": %s,
        "api": "%s"
    },`
			configStr += fmt.Sprintf(tpl, field.GetConfig().CnName, field.GetName(), tool.CreateRand(10), field.GetSrc())
		case "M2M":
			tpl = `{
        "label": "%s",
        "key": "%s",
        "type": "EzCheckboxApi",
        "span": 24,
        "placeholder": "请输入",
        "sn": %s,
        "api": "%s"
    },`
			configStr += fmt.Sprintf(tpl, field.GetConfig().CnName, field.GetName(), tool.CreateRand(10), field.GetSrc())
		default:
			tpl = `{
        "label": "%s",
        "key": "%s",
        "type": "EzText",
        "span": 24,
        "placeholder": "请输入",
        "sn": %s
    },`
			configStr += fmt.Sprintf(tpl, field.GetConfig().CnName, field.GetName(), tool.CreateRand(10))
		}
	}
	return configStr
}

func makeListItem(creator *Creator) string {
	configStr := ""
	for _, field := range creator.Fields {

		var tpl = `{
            title: "%s",
            name: "%s",
            key: "%s",
            width: 200,
            showType: "text",
            links: "",
            realWidth: 200
        },`
		configStr += fmt.Sprintf(tpl, field.GetConfig().CnName, field.GetName(), field.GetName())
	}
	return configStr
}
